package com.util.dao.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.util.dao.BasicDao;

@Repository("basicDao")
public class BasicDaoImpl extends HibernateDaoSupport implements BasicDao{

		@Transactional(propagation = Propagation.REQUIRED,readOnly=false)
		public <T> void insert(T t) throws Exception {
			getHibernateTemplate().save(t);
		}
		
	  @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void deleteAll(Collection<T> entities) {
	        getHibernateTemplate().deleteAll(entities);
	    }

	    @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void insertAll(Collection<T> t) throws Exception {
	       for(T obj : t){
	           getHibernateTemplate().save(obj);
	       }
	    }
	    
	    @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void delete(T obj) throws Exception {
	        getHibernateTemplate().delete(obj);
	    }

	    @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void update(T t) throws Exception {
	        // session().update(obj);
	        getHibernateTemplate().update(t);
	    }

	    @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void saveOrUpdate(T t) throws Exception {
	        getHibernateTemplate().saveOrUpdate(t);
	    }

	    public <T, I extends Serializable> T queryById(Class<T> clazz, I id) throws Exception {
	        return (T) getHibernateTemplate().get(clazz, id);
	    }

	    @SuppressWarnings("unchecked")
	    public <T> List<T> queryByPage(String hql, int firstResult, int num) throws Exception {
	        Query query = getSession().createQuery(hql);
	        query.setFirstResult(firstResult);
	        query.setMaxResults(num);
	        return (List<T>) query.list();
	    }

	    @SuppressWarnings("unchecked")
	    public <T> Collection<T> queryByExampleEntity(Class<T> clazz, T exampleEntity, int firstResult,
	            int maxResults) throws Exception {
	        return (Collection<T>) getHibernateTemplate().findByExample(clazz.getName(), exampleEntity,
	                firstResult, maxResults);
	    }

	    @Transactional(propagation = Propagation.REQUIRED)
	    public <T> void merge(T t) throws Exception {
	        getHibernateTemplate().merge(t);
	    }

}
